package com.toolkit.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class TwoDimensionCodeUtils {
	
	//定义颜色的二进制
	//黑色
	private static final int BLACK = 0xFF000000;  
	//白色
    private static final int WHITE = 0xFFFFFFFF;  
    //嵌入二维码图片的宽度
  	private static final int IMAGE_WIDTH = 60;
    //嵌入二维码图片的高度
    private static final int IMAGE_HEIGHT = 60; 
    //嵌入二维码图片宽度的一半
    private static final int IMAGE_HALF_WIDTH = IMAGE_WIDTH / 2; 
    //嵌入二维码图片边框宽度
    private static final int FRAME_WIDTH = 2;
	
    /**
     * 生成中间不带图片的二维码图像文件
     * @param width 二维码宽度(400-500)
     * @param height 二维码高度(400-500)
     * @param content 所要生成的二维码内容
     * @param format 生成二维码图片格式 如 gif jpg png..
     * @param outputFilePath 二维码图片生成后存放路径
     * @return 生成成功返回TRUE 生成失败返回false
     * @throws WriterException
     * @throws IOException
     */
    public static boolean encodeTwoDimensionCode(int width, int height, String content, String format, String outputFilePath) throws WriterException, IOException {
    	
    	//调用生成中间不带图片的二维码图像的方法
    	BufferedImage image = generateBarcode(content,width,height);  
    	File outputFile = new File(outputFilePath);
        if (!ImageIO.write(image, format, outputFile)) {  
        	return false;
        }
    	return true;
    }
    
	/**
     * 生成中间带图片的二维码图像文件
     * @param width 二维码宽度(400-500)
     * @param height 二维码高度(400-500)
     * @param content 所要生成的二维码内容
     * @param format 生成二维码图片类型 如 gif jpg png..
     * @param outputFilePath 二维码图片生成后存放路径
     * @param sourceImageFilePath 二维码中间所加图片路径
     * @return 生成成功返回TRUE 生成失败返回false
     * @throws WriterException
     * @throws IOException
     */
    public static boolean encodeTwoDimensionCodeWithMidImage(int width, int height,String content,String format,String outputFilePath,String sourceImageFilePath) throws WriterException, IOException {
    	
    	//调用生成中间带图片的二维码图像的方法
    	BufferedImage image = generateBarcodeWithMidImage(content, width, height, sourceImageFilePath);
    	File outputFile = new File(outputFilePath);
    	outputFile.mkdirs();
    	if (!ImageIO.write(image, format, outputFile)) {
    		return false;
  	    }
    	return true;
    }
    
    /**
     * 生成中间不带图片的二维码图像
     * @param content 所要生成的二维码内容
     * @param width 二维码宽度(400-500)
     * @param height 二维码高度(400-500)
     * @return 返回中间不带图片的二维码图像
     * @throws WriterException
     */
    @SuppressWarnings("unchecked")
	public static BufferedImage generateBarcode(String content, int width, int height) throws WriterException {  
    	
		@SuppressWarnings("rawtypes")
		Hashtable hints = new Hashtable();  
        //内容所使用编码  
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  
    	BitMatrix matrix = new MultiFormatWriter().encode(content,  
                BarcodeFormat.QR_CODE, width, height, hints);  
    	//二维码矩阵宽度
        int tDCWidth = matrix.getWidth(); 
        //二维码矩阵高度
        int tDCHeight = matrix.getHeight();  
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
        for (int x = 0; x < tDCWidth; x++) {  
          for (int y = 0; y < tDCHeight; y++) {  
            image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);  
          }  
        }  
        return image;  
      }  

    
    /**
     * 生成中间带图片的二维码图像
     * @param content 所要生成的二维码内容
     * @param width 二维码宽度
     * @param height 二维码高度
     * @param srcImagePath 二维码中间所加图片路径
     * @return 返回中间带图片的二维码图像
     * @throws WriterException
     * @throws IOException
     */
    public static BufferedImage generateBarcodeWithMidImage(String content, int width,  
            int height, String srcImagePath) throws WriterException,  
            IOException {  
        // 读取源图像  
        BufferedImage scaleImage = scale(srcImagePath, IMAGE_WIDTH,  
                IMAGE_HEIGHT, true);  
        int[][] srcPixels = new int[IMAGE_WIDTH][IMAGE_HEIGHT];  
        for (int i = 0; i < scaleImage.getWidth(); i++) {  
            for (int j = 0; j < scaleImage.getHeight(); j++) {  
                srcPixels[i][j] = scaleImage.getRGB(i, j);  
            }  
        }  
   
        Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();  
        hint.put(EncodeHintType.CHARACTER_SET, "utf-8");  //内容编码
        hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//错误等级
        hint.put(EncodeHintType.MARGIN, 1); //设置二维码外边框的空白区域的宽度
        // 生成二维码
        MultiFormatWriter mutiWriter = new MultiFormatWriter();
        BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE,  
                width, height, hint);  
   
        // 二维矩阵转为一维像素数组  
        int halfW = matrix.getWidth() / 2;  
        int halfH = matrix.getHeight() / 2;  
        int[] pixels = new int[width * height];  
   
        for (int y = 0; y < matrix.getHeight(); y++) {  
            for (int x = 0; x < matrix.getWidth(); x++) {  
                // 读取图片  
                if (x > halfW - IMAGE_HALF_WIDTH  
                        && x < halfW + IMAGE_HALF_WIDTH  
                        && y > halfH - IMAGE_HALF_WIDTH  
                        && y < halfH + IMAGE_HALF_WIDTH) {  
                    pixels[y * width + x] = srcPixels[x - halfW  
                            + IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];  
                }   
                // 在图片四周形成边框  
                else if ((x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH  
                        && x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH  
                        && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH  
                        + IMAGE_HALF_WIDTH + FRAME_WIDTH)  
                        || (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH  
                                && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH  
                                && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH  
                                + IMAGE_HALF_WIDTH + FRAME_WIDTH)  
                        || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH  
                                && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH  
                                && y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH  
                                - IMAGE_HALF_WIDTH + FRAME_WIDTH)  
                        || (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH  
                                && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH  
                                && y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH  
                                + IMAGE_HALF_WIDTH + FRAME_WIDTH)) {  
                    pixels[y * width + x] = WHITE;  
                } else {  
                    // 此处可以修改二维码的颜色，可以分别制定二维码和背景的颜色；  
                    pixels[y * width + x] = matrix.get(x, y) ? BLACK  
                            : WHITE;  
                }  
            }  
        }  
   
        BufferedImage image = new BufferedImage(width, height,  
                BufferedImage.TYPE_INT_RGB);  
        image.getRaster().setDataElements(0, 0, width, height, pixels);  
   
        return image;  
    }  
    
    /** 
     * 把传入的原始图像按高度和宽度进行缩放，生成符合要求的图标 
     * @param srcImageFile 图片源文件地址 
     * @param height 生成图片目标高度 
     * @param width 生成图片目标宽度 
     * @param hasFiller 比例不对时是否需要补白：true为补白; false为不补白; 
     * @throws IOException 
     */  
	private static BufferedImage scale(String srcImageFile, int height,  
            int width, boolean hasFiller) throws IOException {  
        double ratio = 0.0; // 缩放比例  
        File file = new File(srcImageFile);  
        BufferedImage srcImage = ImageIO.read(file);  
        Image destImage = srcImage.getScaledInstance(width, height,  
                BufferedImage.SCALE_SMOOTH);  
        // 计算比例  
        if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {  
            if (srcImage.getHeight() > srcImage.getWidth()) {  
                ratio = (Integer.valueOf(height)).doubleValue()
                        / srcImage.getHeight();  
            } else {  
                ratio = (Integer.valueOf(height)).doubleValue()
                        / srcImage.getWidth();  
            }  
            AffineTransformOp op = new AffineTransformOp(  
                    AffineTransform.getScaleInstance(ratio, ratio), null);  
            destImage = op.filter(srcImage, null);  
        }  
        if (hasFiller) {// 补白  
            BufferedImage image = new BufferedImage(width, height,  
                    BufferedImage.TYPE_INT_RGB);  
            Graphics2D graphic = image.createGraphics(); 
            //边框颜色
            graphic.setColor(Color.white); 
            graphic.fillRect(10, 10, width, height);  
            graphic.drawRect(100, 360, width, height);
            if (width == destImage.getWidth(null)) { 
                graphic.drawImage(destImage, 0,  
                        (height - destImage.getHeight(null)) / 2,  
                        destImage.getWidth(null), destImage.getHeight(null),  
                        Color.white, null);  
                Shape shape = new RoundRectangle2D.Float(0, (height - destImage.getHeight(null)) / 2, width, width, 20, 20);
                graphic.setStroke(new BasicStroke(5f));
                graphic.draw(shape);
            }
            else  {
                graphic.drawImage(destImage,  
                        (width - destImage.getWidth(null)) / 2, 0,  
                        destImage.getWidth(null), destImage.getHeight(null),  
                        Color.white, null);
                Shape shape = new RoundRectangle2D.Float((width - destImage.getWidth(null)) / 2, 0, width, width, 20, 20);
                graphic.setStroke(new BasicStroke(5f));
                graphic.draw(shape);
            }
            graphic.dispose();  
            destImage = image;  
           
        }  
        return (BufferedImage) destImage;  
    } 
	
	/**
	 * 解析二维码文件成字符串
	 * @param decodeFilePath 要解析的二维码文件路径
	 * @return 二维码内容字符串
	 * @throws IOException
	 * @throws NotFoundException
	 */
	public static String decodeTwoDiMensionCode(String decodeFilePath) throws IOException, NotFoundException{
		BufferedImage image;
		image = ImageIO.read(new File(decodeFilePath));
		LuminanceSource source = new BufferedImageLuminanceSource(image);
		Binarizer binarizer = new HybridBinarizer(source);
		BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
		Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();             
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");              
        Result result = new MultiFormatReader().decode(binaryBitmap, hints);
		return result.toString();
	}
	
//	public static void main(String[] args) throws WriterException, IOException, NotFoundException{
//		StringBuffer testCode = new StringBuffer();
//		testCode.append("1111,1234567890,马艳东,北京-内蒙古,2016-09-07,1,1050.00,17.00,0.00,1067.00,1567.00");
//		StringBuffer testCode2 = new StringBuffer();
//		testCode2.append("1111,1234567890,马艳东,北京-内蒙古,2016-09-07,1,1050.00,17.00,0.00,1067.00,1567.00**1111,1234567890,马艳东,北京-内蒙古,2016-09-07,1,1050.00,17.00,0.00,1067.00,1567.00");
//		StringBuffer testCode3 = new StringBuffer();
//		testCode3.append("1111,1234567890,马艳东,北京-内蒙古,2016-09-07,1,1050.00,17.00,0.00,1067.00,1567.00**1111,1234567890,马艳东,北京-内蒙古,2016-09-07,1,1050.00,17.00,0.00,1067.00,1567.00**1111,1234567890,马艳东,北京-内蒙古,2016-09-07,1,1050.00,17.00,0.00,1067.00,1567.00");
////		JSONObject jsonObject = new JSONObject();
////		jsonObject.put("testCode",testCode.toString());
//		boolean success = encodeTwoDimensionCodeWithMidImage(500,500,testCode3.toString(),"png","D:\\hehe3.png","D:\\avic.png");
//		//String code = decodeTwoDiMensionCode("D:\\hehe.png");
////		System.out.println(jsonObject.toString().length());
//		//System.out.println(code);
//		
//	}
}
